<template>
  <div>
   <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意: 只允许为第三级分类设置参数！" type="warning" :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <!-- 一般级联选择框，不用提交就不用form了 -->
          <span>选择商品分类:
            <el-cascader :options="cateList" :props="cateProps" v-model="selectedCateKeys" @change="handleChange"
            clearable></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many" :disabled="isBtnDisabled">
          <el-row>
            <el-col>
              <el-button type="primary" size="mini" @click="addDialogVisible=true" :disabled="isBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" v-slot="{row}">
              <el-tag :key="i" v-for="(item, i) in row.attr_vals" closable @close="handleClose(i, row)">
                {{item}}
              </el-tag>
              <!-- 输入文本框，失去焦点/enter都会再次变回button-->
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
              size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
              </el-input>
              <!-- 添加按钮 -->
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" v-slot="{row}">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row.attr_id)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(row.attr_id)">删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态参数面板 -->
        <el-tab-pane label="静态属性" name="only" :disabled="isBtnDisabled">
          <el-row>
            <el-col>
              <el-button type="primary" size="mini" @click="addDialogVisible=true">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table :data="anyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" v-slot="{row}">
              <el-tag :key="i" v-for="(item, i) in row.attr_vals" closable @close="handleClose(i, row)">
                {{item}}
              </el-tag>
              <!-- 输入文本框，失去焦点/enter都会再次变回button-->
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
              size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
              </el-input>
              <!-- 添加按钮 -->
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作" v-slot="{row}">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row.attr_id)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(row.attr_id)">删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 添加分类的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 修改参数/属性对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 添加分类的表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框配置对象
      cateProps: {
        // hover触发
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向选中的数据数组
      selectedCateKeys: [],
      // 被激活的页签名
      activeName: 'many',
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      anyTableData: [],
      // 添加属性/参数对话框显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {},
      // 添加参数表单的验证规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改对话框显示与隐藏
      editDialogVisible: false,
      // 修改的表单数据
      editForm: {},
      // 修改的表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败!')
      this.cateList = res.data
    },
    // 级联选择框数据变化触发
    handleChange () {
      this.getParamsData()
    },
    // Tab页签点击触发事件
    handleTabClick () {
      this.getParamsData()
    },
    // 获取参数列表
    async getParamsData() {
      // 要求选中的必须是三级分类，所以不是三级分类则清空
      if (this.selectedCateKeys.length !== 3) {
        // 把表单数据清空，也把表格数据清空
        this.selectedCateKeys = []
        this.manyTableData = []
        this.anyTableData = []
      } else {
        const { data: res } = await this.axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败!')
        res.data.forEach(item => {
          // 把字符串变成数组，方便for循环渲染
          // 先判断是否为空，由于数组原因，空字符串也会被循环出一个结果
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制添加文本框的显示与隐藏,必须要添加，防止多行数据冲突
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.anyTableData = res.data
        }
      }
    },
    // 监听对话框关闭事件
    addDialogClosed () {
      // 关闭后重置验证结果
      this.$refs.addFormRef.resetFields()
    },
    // 对话框确定添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.$message.success('添加参数成功!')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击编辑修改参数
    async showEditDialog(attrId) {
      this.editDialogVisible = true
      // 查询当前修改的参数(分类id和参数id不一样哟)
      const { data: res } = await this.axios.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('查询参数信息失败!')
      this.editForm = res.data
    },
    // 监听修改对话框关闭事件
    editDialogClosed () {
      // 清空表单
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮修改参数信息
    async editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name, attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('编辑参数失败！')
        this.$message.success('编辑数据成功!')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击删除参数/属性
    async removeParams(attrId) {
      // 这也是一个异步操作，别忘了
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 如果取消了删除
      if (confirmResult !== 'confirm') return this.$message.info('已取消了删除！')
      // 没有取消，直接删除
      const { data: res } = await this.axios.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error('删除属性失败！')
      this.$message.success('删除属性成功！')
      this.getParamsData()
    },
    // 文本框失去了焦点或按下了enter键就显示button
    async handleInputConfirm (row) {
      // 如果输入的字符不为空，则后续处理(添加)
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim())
        // 如果为空直接清除，或者添加完成后也需要清除
        row.inputValue = ''
        row.inputVisible = false
        // 发起网络请求，将数据永久保存到数据库中
        this.saveAttrVals(row)
      } else {
        row.inputValue = ''
        row.inputVisible = false
      }
    },
    // 点击了添加按钮
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点，元素被重新渲染之后才能拿到这个input
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 将对attr_vals的操作保存到数据库
    async saveAttrVals (row) {
      const { data: res } = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败!')
      this.$message.success('修改参数项成功!')
    },
    // 删除参数可选项
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 如果按钮需要被禁用,则返回true,否则返回false
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的分类id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 添加参数/属性对话框标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  components: {}
}
</script>

<style lang="scss" scoped>
.cat_opt{
  margin: 15px 0;
}
.el-tag{
  margin: 5px;
}
.input-new-tag{
  width: 120px;
}
</style>
